﻿
using ScanSnap.Domain;
using ScanSnap.Domain.JSON;
using ScanSnap.Domain.TreeData;
using ScanSnap.Util;
using ScanSnap.Wpf.WpfWindow;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Animation;

namespace ScanSnap.Wpf.WpfPage
{
    public partial class MainApplicationPage : Page
    {

        #region Button Events

        private void ButtonClose_Click(object sender, RoutedEventArgs e)
        {
            IsClosed = true;
            Application.Current.Shutdown();
            Environment.Exit(0);
        }

       
        private void ButtonSignOut_Click(object sender, RoutedEventArgs e)
        {
            MainApplicationPage.instance = null;
            PdfGrabTimerStop();
            MainWindow.Instance.ContentFrame.Content = StartingPage.Instance;            
        }

        private void ButtonFormClear_Click(object sender, RoutedEventArgs e)
        {
            resetUploadForm();
        }

        private void ButtonSearchClear_Click(object sender, RoutedEventArgs e)
        {
            inputValidater(10);
            CategoryA.IsChecked = false;
            CategoryB.IsChecked = false;
            CategoryC.IsChecked = false;

            TextOrganizationSearchId.Text = "";
            ComboOrganizationSearchName.SelectedIndex = 0;
            //TagList.Clear();
            TextPatientSearchId.Text = "";
            ComboPatientSearchName.Text = "";
            ComboRetentionPeriodSearchUnit.SelectedIndex = 0;
            ComboRetentionPeriodSearchValue.SelectedIndex = 0;

            //TreeViewDocumentTypeAC.Visibility = System.Windows.Visibility.Hidden;
            // TreeViewDocumentTypeB.Visibility = System.Windows.Visibility.Hidden;
            BrowserPdfViewer.Source = null;
            //this.Close();
        }

        private void ButtonTagAdd_Click(object sender, RoutedEventArgs e)
        {
            if (CustomTagList != null && TextNewTagName.Text != null && TextNewTagName.Text.Length > 0)
            {
                string newTag = TextNewTagName.Text;
                newTag = newTag.Replace(",", "");
                Random rnd = new Random();
                CustomTagList.Add(new Tag { Id = "TagId_" + rnd.Next(100), Name = newTag });
                ListViewDocumentCustomTag.Items.Refresh();
            }
        }

        private void ButtonFormSubmit_Click(object sender, RoutedEventArgs e)
        {
            SetMessage("", MessageType.CLEAR);

            Duration duration = new Duration(TimeSpan.FromSeconds((30 * 1.35)));
            DoubleAnimation doubleAnimatiion = new DoubleAnimation(200, duration);

            TaskScheduler uiThread = TaskScheduler.FromCurrentSynchronizationContext();

            ValidateButtonFormSubmit();

            if (ErrorList.Count != 0)
            {
                ErrorWindow ew = new ErrorWindow(ErrorList);
                ew.Visibility = System.Windows.Visibility.Visible;
                return;
            }

            SetMessage(InformationMessage.FILE_UPLOAD_STARTED, MessageType.INFO);

            string dateFormat = "yyyy/MM/dd"; // hh:mm:ss tt
            Organization organization = (Organization)ComboOrganizationName.SelectedItem;
            DocumentType docType = (DocumentType)ComboDocumentType.SelectedItem;
            Document mstDocument = (Document)ComboDocumentName.SelectedItem;
            List<Tag> docTag = (List<Tag>)ListViewDocumentTag.ItemsSource;
            List<Tag> customTag = (List<Tag>)ListViewDocumentCustomTag.ItemsSource;

            string retentionValue = ((ComboBoxItem)ComboRetentionPeriodValue.SelectedItem).Content.ToString();
            string retentionUnit = ((ComboBoxItem)ComboRetentionPeriodUnit.SelectedItem).Content.ToString();
            int retentionunitval = ComboRetentionPeriodUnit.SelectedIndex; // 0 - years, 1 - Months, 2 - Weeks, 3 - Days
            DateTime documentUploadDate = DatePickerEventDate.SelectedDate.Value;
            DateTime documentPdfDate = DatePickerPdfDate.SelectedDate.Value;
            DateTime documentRetToDate = DatePickerPdfDate.SelectedDate.Value;

            BooleanConverter bc = new BooleanConverter();
            int hasAttachs = 0;
            hasAttachs = RadioAttachmentYes.IsChecked == true ? 1 : 0;


            Debug.WriteLine("organizationCode       " + organization.Code);
            Debug.WriteLine("organizationID         " + organization.Id);
            Debug.WriteLine("organizationName       " + organization.Name);
            Debug.WriteLine("documentTypeID         " + docType.Id);
            Debug.WriteLine("documentTypeName       " + docType.Name);
            Debug.WriteLine("mstDocumentName        " + mstDocument.Name);
            Debug.WriteLine("mstDocumentID          " + mstDocument.Id);

            Debug.WriteLine("retentionValue         " + retentionValue);
            Debug.WriteLine("retentionUnit          " + retentionUnit);
            Debug.WriteLine("retentionunitval       " + retentionunitval);
            Debug.WriteLine("documentUploadDate     " + documentUploadDate.ToString(dateFormat));
            Debug.WriteLine("documentPdfDate        " + documentPdfDate.ToString(dateFormat));
            Debug.WriteLine("Has Attaches           " + hasAttachs);


            string selectedPath = "";
            string selectedFileName = "";
            foreach (FileEntry f in PdfFileList)
            {
                if (f.IsSelected == true)
                {
                    selectedPath = f.FullName;
                    selectedFileName = f.Name;
                    break;
                }
            }


            int retperiod = int.Parse(retentionValue);
            if (retentionunitval == 0)
            {
                documentRetToDate = documentRetToDate.AddYears(retperiod);
            }
            else if (retentionunitval == 1)
            {
                documentRetToDate = documentRetToDate.AddMonths(retperiod);
            }
            else if (retentionunitval == 2)
            {
                documentRetToDate = documentRetToDate.AddDays(retperiod * 7);
            }
            else if (retentionunitval == 3)
            {
                documentRetToDate = documentRetToDate.AddDays(retperiod);
            }


            Debug.WriteLine("selectedPath " + selectedPath);
            Debug.WriteLine("selectedFileName " + selectedFileName);
            Debug.WriteLine("documentRetToDate " + documentRetToDate.ToString(dateFormat));


            DateTime d = DateTime.Now;
            string df = "yyyyMMddHHmmssFF";
            String savedDocName = d.ToString(df)+".pdf";

            Debug.WriteLine("savedDocName " + savedDocName);

            NameValueCollection vals = new NameValueCollection();
            vals.Add("userDocument.organizationId", organization.Id);
            vals.Add("userDocument.documentName", selectedFileName);
            vals.Add("userDocument.savedDocName", savedDocName);
            vals.Add("documentType.id", docType.Id);
            vals.Add("userDocument.documentCategoryId", mstDocument.Id);
            vals.Add("userDocument.documentAttached", hasAttachs.ToString());
            vals.Add("userDocument.datePdfString", documentPdfDate.ToString(dateFormat));
            vals.Add("userDocument.dateCreatedString", documentUploadDate.ToString(dateFormat));
            vals.Add("userDocument.retentionDateString", documentRetToDate.ToString(dateFormat));
            vals.Add("userDocument.insertStaffId", user.Id);
            vals.Add("userDocument.updateStaffId", user.Id);
            vals.Add("userDocument.retentionPeriod", retentionValue);
            vals.Add("userDocument.retentionUnit", retentionUnit);

            if (docTag != null)
            {

                foreach (Tag ta in docTag)
                {
                    Debug.WriteLine("Dcoument Tag  Is Checked  " + ta.Name + "   " + ta.IsChecked);
                    if (ta.IsChecked)
                    {
                        vals.Add("documentTagsCnt", ta.Name);
                    }
                }
            }

            if (customTag != null)
            {
                foreach (Tag cta in customTag)
                {
                    Debug.WriteLine("Custom Tag  Is Checked  " + cta.Name + "   " + cta.IsChecked);
                    if (cta.IsChecked)
                    {
                        vals.Add("docmentCustomTagsCnt", cta.Name);
                    }
                }
            }
            if (ComboDocumentType.SelectedIndex == 2)
            {
                Debug.WriteLine("Patient Type Selected  " + ComboDocumentType.SelectedIndex);
                //Patient patient = (Patient)ComboPatientName.SelectedItem;
                //Debug.WriteLine("Patient ID      " + patient.Id);
                //vals.Add("userDocument.patientId", patient.Id);

                AssessmentSheet assessmentSheet = (AssessmentSheet)ComboPatientHcsList.SelectedItem;

                Debug.WriteLine("Patient ID:" + assessmentSheet.ClientBasicId);
                vals.Add("userDocument.patientId", assessmentSheet.ClientBasicId);

                Debug.WriteLine("Patient AssessmentSheet ID:" + assessmentSheet.Id);
                vals.Add("userDocument.assessmentSheetId", assessmentSheet.Id);
                Debug.WriteLine("Patient HCS ID:" + assessmentSheet.HcsId);
                vals.Add("userDocument.hcsId", assessmentSheet.HcsId);

                try
                {                   
                    if (pdfLoadingWorker.IsBusy)
                    {
                        this.pdfLoadingWorker.CancelAsync();
                    }
                    //File.Delete(selectedPath);
                }
                catch //(IOException ex)
                {
                    //ErrorList = new List<string>();
                    //ErrorList.Add("ファイルは既にアップロードされました");
                    //new ErrorWindow(ErrorList).Show();
                    SetMessage("ファイルは既にアップロードされました", MessageType.ERROR);
                    return;
                }
                finally
                {
                    if (!pdfLoadingWorker.IsBusy)
                    {
                        this.pdfLoadingWorker.RunWorkerAsync();
                    }
                }


            }
            else if (ComboDocumentType.SelectedIndex == 1 || ComboDocumentType.SelectedIndex == 3)
            {

                Debug.WriteLine("Organization Type Selected  " + ComboDocumentType.SelectedIndex);
                try
                {                   
                    if (pdfLoadingWorker.IsBusy)
                    {
                        this.pdfLoadingWorker.CancelAsync();
                        // File.Delete(selectedPath);
                    }
                }
                catch //(IOException ex)
                {
                    //ErrorList = new List<string>();
                    //ErrorList.Add("ファイルは既にアップロードされました");
                    //new ErrorWindow(ErrorList).Show();
                    SetMessage("ファイルは既にアップロードされました", MessageType.ERROR);

                    return;
                }
                finally
                {
                    if (!pdfLoadingWorker.IsBusy)
                    {
                        this.pdfLoadingWorker.RunWorkerAsync();
                    }
                }

            }

            Action MainThreadDoWork = new Action(() =>
            {

                try
                {
                    StringJSON result = HttpProxy.HttpDocumentUploadFacility<StringJSON>(ApplicationSettings.SERVER_URL + "/persist/persist-user-document-json.html", @selectedPath, "file", "application/octet-stream", vals);
                    if (result != null)
                    {
                        Debug.WriteLine("User Document File Upload Attemt VIA HttpDocumentUploadFacility in HttpProxy    " + result.stringValue);
                        if (result.stringValue.Equals("SUCCESS"))
                        {
                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                SetMessage(InformationMessage.FILE_UPLOADED, MessageType.INFO);

                                File.Delete(selectedPath);
                                refreshPdfFileList();
                            }));
                        }
                        else
                        {
                            String messagecnt = "Unable To Process the Upload Request";
                            if (result.stringValue.Equals("ERROR_DB_PERSIST"))
                            {
                                messagecnt += "\nError while saving data to the Database";
                            }
                            if (result.stringValue.Equals("ERROR_INVALID_DATA"))
                            {
                                messagecnt += "\nInvalid Data Provided";
                            }
                            if (result.stringValue.Equals("ERROR_DATA_READ"))
                            {
                                messagecnt += "\nError While Retrieving Data From Database";
                            }
                            if (result.stringValue.Equals("ERROR_DIR_IOEXC"))
                            {
                                messagecnt += "\nError While Saving the file to Diretories";
                            }
                            if (result.stringValue.Equals("ERROR"))
                            {
                                messagecnt += "\nServer reported an Unknown Error";
                            }

                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                SetMessage(messagecnt, MessageType.ERROR);
                            }));
                        }

                        //new ConfirmationWindow().Show();
                    }
                    else
                    {
                        this.Dispatcher.Invoke((Action)(() =>
                        {
                            SetMessage(ErrorMessage.FILE_CANNOT_UPLOAD_SERVER_ERROR, MessageType.ERROR);
                        }));
                    }
                }
                catch (WebException)
                {
                    this.Dispatcher.Invoke((Action)(() =>
                    {
                        SetMessage(ErrorMessage.FILE_CANNOT_UPLOAD_SERVER_ERROR, MessageType.ERROR);
                    }));

                }
            });

            Action ExecuteProgressBar = new Action(() =>
            {
                ProgressBarUpload.Visibility = System.Windows.Visibility.Visible;
            });

            Action FinalThreadDoWOrk = new Action(() =>
            {
                ProgressBarUpload.Visibility = System.Windows.Visibility.Hidden;
            });

            Task MainThreadDoWorkTask = Task.Factory.StartNew(() => MainThreadDoWork());

            Task ExecuteProgressBarTask = new Task(ExecuteProgressBar);
            ExecuteProgressBarTask.RunSynchronously();

            MainThreadDoWorkTask.ContinueWith(t => FinalThreadDoWOrk(), uiThread);

            if (RadioCacheNo.IsChecked == true)
            {
                resetUploadForm();
            }

        }

        private void ButtonFileDelete_Click(object sender, RoutedEventArgs e)
        {
            PdfGrabTimerStop();
            ConfirmationWindow cw = new ConfirmationWindow("確認を削除", "あなたはそれを削除してもよろしいですか？");//Delete Confirmation, Do you want to delete it?
            cw.ShowDialog();
            MessageBoxResult messageBoxResult = ConfirmationWindow.IsConfirm();

           //// MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Are you sure?", "Delete Confirmation", System.Windows.MessageBoxButton.YesNo);
            if (messageBoxResult == MessageBoxResult.Yes)
            {                
                try
                {
                    foreach (FileEntry f in PdfFileList)
                    {
                        if (f.IsSelected == true)
                        {
                            //FileInfo fileInfo = new FileInfo(f.FullName);
                            //fileInfo.IsReadOnly = false;
                            //fileInfo.Refresh();
                            File.Delete(f.FullName);
                            refreshPdfFileList();
                            break;
                        }
                    }
                }
                catch (Exception)
                {
                    SetMessage(ErrorMessage.FILE_CANNOT_DELETE, MessageType.ERROR);
                }
            }

            PdfGrabTimerStart();
            
        }

        private void ButtonFormFinish_Click(object sender, RoutedEventArgs e)
        {
            //this.Close();
        }

        private void ButtonSearchSubmit_Click(object sender, RoutedEventArgs e)
        {
            SetMessage2("", MessageType.CLEAR);
            SubmitSearchValidation();
            if (ErrorList.Count != 0)
            {
                ErrorWindow ew = new ErrorWindow(ErrorList);
                ew.Visibility = System.Windows.Visibility.Visible;
                return;
            }

            try
            {
                string retUnit = "YEARS";
                if (searchMonth.IsSelected) retUnit = "MONTHS";
                else if (searchWeek.IsSelected) retUnit = "WEEKS";
                else if (searchDay.IsSelected) retUnit = "DAYS";

                ListBoxItem rplbi = (ListBoxItem)ComboRetentionPeriodSearchValue.SelectedItem;
                string retPeriod = rplbi.Content.ToString();
                Debug.WriteLine("ret value  " + rplbi.Content);
                string dateFormat = "MMMM dd, yyyy hh:mm:ss tt";
                DateTime docStartDate = DatePickerRangeStartDate.SelectedDate.Value;
                DateTime docEndDate = DatePickerRangeEndDate.SelectedDate.Value;
                Organization selectedOrg = (Organization)ComboOrganizationSearchName.SelectedItem;
                DocumentType selectedDocType = (DocumentType)ComboDocumentTypeSearch.SelectedItem;
                Patient selectedPatient;
                System.Collections.IList selectedDocs = ListViewDocumentNames.SelectedItems;
                System.Collections.IList selectedTags = ListViewDocumentSearchTag.SelectedItems;
                System.Collections.IList selectedCusTags = ListViewDocumentSearchCustomTag.SelectedItems;

                NameValueCollection NVals = new NameValueCollection();
                //NVals.Add("documentSearchInputParams.retentionStartDate", retStartDate.ToString(dateFormat));

                if (Calender.IsChecked == true)
                {
                    NVals.Add("documentSearchInputParams.documentStartDate", docStartDate.ToString(dateFormat));
                    NVals.Add("documentSelectType", "calender");  
                }
                else if (Unit.IsChecked == true)
                {
                    NVals.Add("documentSearchInputParams.retentionPeriod", retPeriod);
                    NVals.Add("documentSearchInputParams.retentionUnit", retUnit);
                    NVals.Add("documentSelectType", "unit");  
                }

                NVals.Add("documentSearchInputParams.documentEndDate", docEndDate.ToString(dateFormat));
                NVals.Add("documentSearchInputParams.organizationId", selectedOrg.Id);
                NVals.Add("documentSearchInputParams.organizationCode", selectedOrg.Code);
                NVals.Add("documentSearchInputParams.documentTypeId", selectedDocType.Id);

                Debug.WriteLine("Docs   " + selectedDocs.Count + "        Tags   " + selectedTags.Count + "       Cus  " + selectedCusTags.Count);

                Debug.WriteLine("Selected Org " + selectedOrg.Name);
                Debug.WriteLine("Selected DocType " + selectedDocType.Name + "  " + selectedDocType.Id);
                foreach (Object obj in selectedDocs)
                {
                    Document doc = (Document)obj;
                    Debug.WriteLine("Document name   " + doc.Name + "  Doc Id   :  " + doc.Id + "    DocTypeID  :  " + doc.DocumentTypeId);
                    NVals.Add("documentSearchInputParams.documentNamesString", doc.Id);
                }
                foreach (Object obj in selectedTags)
                {
                    Tag tag = (Tag)obj;
                    Debug.WriteLine("Document Tag   " + tag.Name);
                    NVals.Add("documentSearchInputParams.tagContentsString", tag.Name);
                }
                foreach (Object obj in selectedCusTags)
                {
                    Tag cusTag = (Tag)obj;
                    Debug.WriteLine("Document cusTag   " + cusTag.Name);
                    NVals.Add("documentSearchInputParams.customTagContentsString", cusTag.Name);
                }
                if (selectedDocType != null)
                {
                    if (selectedDocType.Name.StartsWith("B"))
                    {
                        selectedPatient = (Patient)ComboPatientSearchName.SelectedItem;
                        Debug.WriteLine("Selected Patient " + selectedPatient.Name);
                        NVals.Add("documentSearchInputParams.patientHcsId", selectedPatient.Id);
                        NVals.Add("documentSearchInputParams.patientId", selectedPatient.Id);
                        OrganizationTree ot = JsonService.SearchDocuments4JsonTree(NVals);
                        DocumentTree.Items.Clear();
                        DocumentTree.Items.Add(ot);
                    }
                    else
                    {
                        OrganizationTree ot = JsonService.SearchDocuments4JsonTree(NVals);
                        DocumentTree.Items.Clear();
                        DocumentTree.Items.Add(ot);
                    }
                }
            }
            catch (Exception ex)
            {
                SetMessage2(ErrorMessage.DOCUMENT_SEARCH_ERROR, MessageType.ERROR);
                Debug.WriteLine("Error occured searching documents  " + ex.Message);
            }

        }

        #endregion

        #region TextBox Events

        private void TextPatientId_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Return)
            {
                if (PatientList != null)
                {
                    Patient p = PatientList.Find(x => x.Id == TextPatientId.Text);

                    if (p != null)
                    {
                        ComboPatientName.SelectedItem = p;
                    }

                    SetPatientProperties(p);
                }

            }
        }

        private void TextPatientSearchId_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Return)
            {
                if (PatientList != null)
                {
                    Patient p = PatientList.Find(x => x.Id == TextPatientSearchId.Text);

                    if (p != null)
                    {
                        ComboPatientSearchName.SelectedItem = p;
                    }
                    else
                    {
                        ComboPatientSearchName.SelectedIndex = 0;
                    }
                }

            }
        }

        private void TextOrganizationId_LostFocus(object sender, RoutedEventArgs e)
        {
            string code = TextOrganizationId.Text;

            if (this.Organizations != null)
            {
                foreach (Organization o in Organizations)
                {
                    if (o.Code.Equals(code))
                    {
                        ComboOrganizationName.SelectedValue = o.Code;
                        return;
                    }
                }
            }

            ComboOrganizationName.SelectedIndex = 0;
            TextOrganizationId.Text = INVALID_ID;

        }

        private void TextOrganizationSearchId_LostFocus(object sender, RoutedEventArgs e)
        {
            string id = TextOrganizationSearchId.Text;
            Organization org;

            org = Organizations.Find(x => x.Id == id);

            if (org != null)
            {
                ComboOrganizationSearchName.SelectedValue = org.Id;
                TextOrganizationSearchId.Text = org.Id;
            }
            else
            {
                ComboOrganizationSearchName.SelectedIndex = 0;
                TextOrganizationSearchId.Text = INVALID_ID;
            }
        }

        private void TextOrganizationId_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Return)
            {
                Organization org = FindOrganizationByCode(TextOrganizationId.Text);

                if (org == null)
                {
                    ResetOrganizationNotFound();
                }
                else
                {
                    ComboOrganizationName.SelectedItem = org;
                }
            }
        }

        private void TextOrganizationSearchId_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Return)
            {
                Organization org = FindOrganizationByCode(TextOrganizationSearchId.Text);

                if (org == null)
                {
                    ComboOrganizationSearchName.SelectedIndex = 0;
                }
                else
                {
                    ComboOrganizationSearchName.SelectedItem = org;
                }
            }
        }

        #endregion

        #region ComboBox Events

        private void ComboPatientName_Click(object sender, RoutedEventArgs e)
        {

            Patient p = (Patient)ComboPatientName.SelectedItem;

            SetPatientProperties(p);           

        }


        private void ComboPatientHcsId_Click(object sender, SelectionChangedEventArgs e)
        {
            AssessmentSheet AS = (AssessmentSheet)ComboPatientHcsList.SelectedItem;

            if (AS != null)
                LabelPatientAddress.Content = AS.Address1 + " " + AS.Address2;
            else
                LabelPatientAddress.Content = "";
        }

        private void ComboPatientSearchName_Click(object sender, SelectionChangedEventArgs e)
        {
            Patient p = (Patient)ComboPatientSearchName.SelectedItem;

            if (p != null)
                TextPatientSearchId.Text = p.Id;
            else
                TextPatientSearchId.Text = INVALID_ID;
        }


        private void ComboOrganizationName_Click(object sender, RoutedEventArgs e)
        {
            SetMessage("", MessageType.CLEAR);
            if (ComboOrganizationName.SelectedIndex != 0)
            {
                Organization organization = (Organization)ComboOrganizationName.SelectedItem;
                if (organization != null)
                {
                    try
                    {
                        PatientList = JsonService.PatientsByOrganizationidJSON(organization.Id);

                        if (PatientList != null)
                        {
                            TextOrganizationId.Text = organization.Code;
                            ComboPatientName.ItemsSource = PatientList;
                        }
                        else
                        {
                            TextOrganizationId.Text = "";
                            ComboPatientName.ItemsSource = null;
                            SetMessage(ErrorMessage.PATIENT_LIST_LOADING_ERROR, MessageType.ERROR);
                            TextOrganizationId.Text = DefaultValue.ORGANIZATION_ID_DEFAULT;
                        }

                    }
                    catch (WebException)
                    {
                        SetMessage(ErrorMessage.SERVER_CONNECT_ERROR, MessageType.ERROR);
                        TextOrganizationId.Text = DefaultValue.ORGANIZATION_ID_DEFAULT;
                    }
                }
            }
            else
            {
                TextOrganizationId.Text = DefaultValue.ORGANIZATION_ID_DEFAULT;
            }
        }

        private void ComboOrganizationSearchName_Click(object sender, SelectionChangedEventArgs e)
        {
            inputValidater(0);
            if (ComboOrganizationSearchName.SelectedIndex != 0)
            {
                Organization organization = (Organization)ComboOrganizationSearchName.SelectedItem;
                if (organization != null)
                {
                    try
                    {
                        PatientList = JsonService.PatientsByOrganizationidJSON(organization.Id);
                        TextOrganizationSearchId.Text = organization.Code;
                        if (PatientList != null)
                        {
                            //TextOrganizationSearchId.Text = organization.Code;
                            ComboPatientSearchName.ItemsSource = PatientList;


                        }
                        else
                        {
                            SetMessage2(ErrorMessage.PATIENT_LIST_LOADING_ERROR, MessageType.ERROR);
                            //TextOrganizationSearchId.Text = DefaultValue.ORGANIZATION_ID_DEFAULT;
                        }

                    }
                    catch (WebException)
                    {
                        SetMessage2(ErrorMessage.SERVER_CONNECT_ERROR, MessageType.ERROR);
                        TextOrganizationSearchId.Text = DefaultValue.ORGANIZATION_ID_DEFAULT;
                        ComboDocumentTypeSearch.IsEnabled = false;
                        //ComboDocumentSearchName.IsEnabled = false;
                    }
                }
            }
            else
            {
                TextOrganizationSearchId.Text = DefaultValue.ORGANIZATION_ID_DEFAULT;
            }
        }

        private List<ComboBoxItem> setRetentionPeriodList(int count)
        {
            List<ComboBoxItem> list = new List<ComboBoxItem>();

            for(int i=0; i<count; i++)
            {
                ComboBoxItem cbi = new ComboBoxItem();
                cbi.Name = "search"+(i+1);
                cbi.Content = i+1;

                list.Add(cbi);
            }

            return list;
        }

        private void ComboRetentionPeriodUnit_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox cbi = sender as ComboBox;
            ComboBoxItem cb = cbi.SelectedItem as ComboBoxItem;

            if(cb != null)
            {
                String str = cb.Name.ToString();
                int selected = ComboRetentionPeriodValue.SelectedIndex;
                int count;

                if (str.Equals("itemDay"))
                {
                    ComboRetentionPeriodValue.ItemsSource = setRetentionPeriodList(7);
                    count = 7;

                }
                else if (str.Equals("itemMonth"))
                {
                    ComboRetentionPeriodValue.ItemsSource = setRetentionPeriodList(12);
                    count = 12;
                }
                else
                {
                    ComboRetentionPeriodValue.ItemsSource = setRetentionPeriodList(5);
                    count = 5;
                }

                if (selected < count && selected != -1)
                {
                    ComboRetentionPeriodValue.SelectedIndex = selected;
                }
                else
                {
                    ComboRetentionPeriodValue.SelectedIndex = count - 1;
                }
            }
        }

        private void ComboRetentionPeriodChange_Click(object sender, RoutedEventArgs e)
        {
            ComboBox cbi = sender as ComboBox;
            ComboBoxItem cb = cbi.SelectedItem as ComboBoxItem;

            String str = cb.Name.ToString();
            int selected = ComboRetentionPeriodSearchValue.SelectedIndex;
            int count;

            if (str.Equals("searchDay"))
            {
                ComboRetentionPeriodSearchValue.ItemsSource = setRetentionPeriodList(7);
                count = 7;

            }
            else if (str.Equals("searchMonth")) 
            {
                ComboRetentionPeriodSearchValue.ItemsSource = setRetentionPeriodList(12);
                count = 12;
            }
            else
            {
                ComboRetentionPeriodSearchValue.ItemsSource = setRetentionPeriodList(5);
                count = 5;
            }

            if (selected < count && selected != -1)
            {
                ComboRetentionPeriodSearchValue.SelectedIndex = selected;
            }
            else
            {
                ComboRetentionPeriodSearchValue.SelectedIndex = count - 1;
            }

            /*
                    * 
                    *
                       if (ComboRetentionPeriodSearchValue != null && ComboRetentionPeriodSearchUnit != null &&
                           DatePickerRangeEndDate != null && DatePickerRangeStartDate != null)
                       {
                           string RetentionPeriodValue = ComboRetentionPeriodSearchValue.SelectedItem.ToString();
                           int RetentionPeriodUnit = ComboRetentionPeriodSearchUnit.SelectedIndex;

                           int PeriodInteger = 5 - Convert.ToInt32(ComboRetentionPeriodSearchValue.SelectedIndex);
                           DateTime dateTime = DatePickerRangeEndDate.SelectedDate.Value;

                           if (RetentionPeriodUnit == 0)
                           {
                               DatePickerRangeStartDate.SelectedDate = dateTime.AddYears(-PeriodInteger);
                           }
                           else if (RetentionPeriodUnit == 1)
                           {
                               DatePickerRangeStartDate.SelectedDate = dateTime.AddMonths(-PeriodInteger);
                           }
                           else if (RetentionPeriodUnit == 2)
                           {
                               DatePickerRangeStartDate.SelectedDate = dateTime.AddDays(-(PeriodInteger * 7));
                           }
                           else
                           {
                               DatePickerRangeStartDate.SelectedDate = dateTime.AddDays(-PeriodInteger);
                           }
                       }
             *  * 
                    * 
                    * */
        }



        private void ComboDocumentType_Change(object sender, RoutedEventArgs e)
        {

            DocumentType d = (DocumentType)ComboDocumentType.SelectedItem;

            if (d != null)
            {
                LoadDocumentNames(d.Id);

                if (d.Name.StartsWith("B"))
                    RowPatientInformation.Visibility = System.Windows.Visibility.Visible;
                else
                    RowPatientInformation.Visibility = System.Windows.Visibility.Hidden;
            }

        }

        private void ComboDocumentTypeSearch_Change(object sender, RoutedEventArgs e)
        {
            inputValidater(1);
            if (ComboDocumentTypeSearch.SelectedIndex > 0)
            {

                DocumentType d = (DocumentType)ComboDocumentTypeSearch.SelectedItem;
                Debug.WriteLine("Comes to the ComboDocumentTypeSearch_Change    " + d.Name);
                LoadDocumentNamesSearch(d.Id);

                if (d.Name.StartsWith("B"))
                    GridPatient.Visibility = System.Windows.Visibility.Visible;
                else
                    GridPatient.Visibility = System.Windows.Visibility.Hidden;

            }

        }

        private void ComboDocumentName_Change(object sender, RoutedEventArgs e)
        {
            Document document = (Document)ComboDocumentName.SelectedItem;
            Organization organization = (Organization)ComboOrganizationName.SelectedItem;
            if (document != null && organization != null && ComboDocumentName.SelectedIndex != 0 && ComboOrganizationName.SelectedIndex != 0)
            {
                LoadTags(organization.Id, document.Id);
            }
            else
            {
                ClearTags();
            }
        }

        /*
         * 
         * 
             private void ComboDocumentSearchName_Change(object sender, RoutedEventArgs e)
             {
                 inputValidater(2);
                 Document document = (Document)ComboDocumentSearchName.SelectedItem;
                 Organization organization = (Organization)ComboOrganizationSearchName.SelectedItem;
                 if (document != null && organization != null && ComboOrganizationSearchName.SelectedIndex != 0 && ComboDocumentSearchName.SelectedIndex != 0)
                 {
                     LoadSearchTags(organization.Id, document.Id);
                 }

             }
         * 
         * 
         * 
         * 
         * */


        private void CheckBox_Click_1(object sender, RoutedEventArgs e)
        {
            isMouseChecked = true;
        }

        private void documentChecked(object sender, RoutedEventArgs e)
        {
            

            Debug.WriteLine("Come to the documentChecked  ");
            if (reloadTags && ComboOrganizationSearchName.SelectedIndex != 0)
            {
                Debug.WriteLine("Come to the documentChecked  22");

                IList selectedDocs = ListViewDocumentNames.SelectedItems;
                Document document = sender as Document;//(Document)ComboDocumentSearchName.SelectedItem;
                Organization organization = (Organization)ComboOrganizationSearchName.SelectedItem;

                if (organization != null && ComboOrganizationSearchName.SelectedIndex != 0)
                {
                    Debug.WriteLine("Come to the documentChecked  33");
                    LoadSearchTags_2(organization.Id, selectedDocs);
                    reloadTags = true;
                    isMouseChecked = false;
                }
            }
        }

        #region Validate Inputs Live

        private void inputValidater(int Object_)
        {
            SetMessage2("", MessageType.CLEAR);
            if (Object_ == 0) // Organization Changed
            {
                BrowserPdfViewer.Source = null;
                //this.AcrobatPdfViewer.Child = null;
                DocumentTree.Items.Clear();
                reloadTags = true;
                ComboDocumentTypeSearch.SelectedIndex = 0;
                ListViewDocumentNames.ItemsSource = null;
                ListViewDocumentNames.Items.Refresh();
                ListViewDocumentNames.Items.Clear();
                ClearSearchTags();

                CheckboxPatientSearch.IsChecked = false;
                GridPatient.Visibility = System.Windows.Visibility.Hidden;

                if (ComboOrganizationSearchName.SelectedIndex == 0)
                {
                    ComboDocumentTypeSearch.IsEnabled = false;
                }
                else
                {
                    ComboDocumentTypeSearch.IsEnabled = true;
                }
            }
            else if (Object_ == 1) // DocType Changed
            {
                BrowserPdfViewer.Source = null;
                //this.AcrobatPdfViewer.Child = null;
                DocumentTree.Items.Clear();
                reloadTags = true;
                ClearSearchTags();
                ListViewDocumentNames.ItemsSource = null;
                ListViewDocumentNames.Items.Refresh();
                ListViewDocumentNames.Items.Clear();
                CheckboxPatientSearch.IsChecked = false;
                if (ComboDocumentTypeSearch.SelectedIndex == 0)
                {
                    GridPatient.Visibility = System.Windows.Visibility.Hidden;
                }



            }
            else if (Object_ == 2) // Document Name Clicked
            {

            }
            else if (Object_ == 10) // Document Search Reset Button Clicked
            {
                BrowserPdfViewer.Source = null;
                //this.AcrobatPdfViewer.Child = null;
                DocumentTree.Items.Clear();
                reloadTags = true;
                ComboDocumentTypeSearch.SelectedIndex = 0;
                ListViewDocumentNames.ItemsSource = null;
                ListViewDocumentNames.Items.Refresh();
                ListViewDocumentNames.Items.Clear();
                ClearSearchTags();

                CheckboxPatientSearch.IsChecked = false;
                GridPatient.Visibility = System.Windows.Visibility.Hidden;
                ComboDocumentTypeSearch.IsEnabled = false;
            }


        }

        #endregion



        #endregion

        #region RadioButon Events

        private void RadioCategory_Check(object sender, RoutedEventArgs e)
        {
            RadioButton RadioCategory = (RadioButton)sender;
            switch (RadioCategory.Name)
            {
                case "CategoryA":
                    CreateCheckBoxList(1);
                    break;
                case "CategoryB":
                    CreateCheckBoxList(2);
                    break;
                case "CategoryC":
                    CreateCheckBoxList(3);
                    break;
                default:
                    CreateCheckBoxList(0);
                    break;
            }
        }

        private void RadioRetentionPeriodYes_Click(object sender, RoutedEventArgs e)
        {
            ComboRetentionPeriodValue.SelectedIndex = 0;
            ComboRetentionPeriodUnit.SelectedIndex = 0;
            BooleanPropertySet(true, ComboRetentionPeriodUnit, ComboRetentionPeriodValue);
        }

        private void RadioRetentionPeriodNo_Click(object sender, RoutedEventArgs e)
        {
            ComboRetentionPeriodValue.Text = "";
            ComboRetentionPeriodUnit.Text = "";
            BooleanPropertySet(false, ComboRetentionPeriodUnit, ComboRetentionPeriodValue);
        }

        public void RadioPdfPageYes_Click(object sender, RoutedEventArgs e)
        {
            BooleanPropertySet(true, DatePickerPdfDate);
        }

        public void RadioPdfPageNo_Click(object sender, RoutedEventArgs e)
        {
            DatePickerPdfDate.Text = "";
            BooleanPropertySet(false, DatePickerPdfDate);
        }

        protected void RadioButtonList_Click(object sender, RoutedEventArgs e)
        {
            ListView listview = sender as ListView;

            RadioButton rb = sender as RadioButton;

            FileEntry fe = new FileEntry();// fe.Content;
            fe.Name = rb.Content.ToString();

            //FileEntry fe = (FileEntry)ListViewFile.Items.GetItemAt(ListViewFile.SelectedIndex);

            List<FileEntry> NewPdfFileList = new List<FileEntry>();

            foreach (FileEntry oldfe in ListViewFile.Items)
            {
                if (oldfe.IsSelected == true)
                {
                    oldfe.IsSelected = false;
                }
                if (fe.Name.Equals(oldfe.Name))
                {
                    oldfe.IsSelected = true;
                    //ListViewFile.Items.
                }
                NewPdfFileList.Add(oldfe);
            }

            PdfFileList = NewPdfFileList;

            ListViewFile.ItemsSource = NewPdfFileList;
            ListViewFile.Items.Refresh();

        }

        #endregion

        #region ListView Events

        private void ListViewFile_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListView listview = sender as ListView;

            FileEntry fe = (FileEntry)listview.Items.GetItemAt(ListViewFile.SelectedIndex);

            List<FileEntry> NewPdfFileList = new List<FileEntry>();

            foreach (FileEntry oldfe in ListViewFile.Items)
            {
                if (oldfe.IsSelected == true)
                {
                    oldfe.IsSelected = false;
                }
                if (fe.Name.Equals(oldfe.Name))
                {
                    oldfe.IsSelected = true;
                }
                NewPdfFileList.Add(oldfe);
            }

            PdfFileList = NewPdfFileList;

            ListViewFile.ItemsSource = NewPdfFileList;

            ListViewFile.Items.Refresh();

        }

        protected void ListViewFile_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            RadioButton rb = sender as RadioButton;

            if (rb != null)
            {
                string pdfFile = rb.Content.ToString();

                string pdfPath = ApplicationSettings.SCAN_FOLDER;
                new BrowserPreview(@pdfPath + "\\" + pdfFile).Show();
            }
        }

        private void ListViewHits_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var item = sender as ListViewItem;
            if (item != null && item.IsSelected)
            {
                Patient p = item.DataContext as Patient;
                BrowserPdfViewer.Source = new Uri(new System.IO.FileInfo(p.DocumentPath).FullName);
               // var PdfUC = new PDFViewerUC(new System.IO.FileInfo(p.DocumentPath).FullName);
                //this.AcrobatPdfViewer.Child = PdfUC;
            }
        }

        #endregion

        #region Checkbox Events

        private void CheckBoxPatientSearch_Check(object sender, RoutedEventArgs e)
        {
            if (CheckboxPatientSearch.IsChecked == true)
            {
                TextPatientSearchId.IsEnabled = true;
                ComboPatientSearchName.IsEnabled = true;
            }
            else
            {
                TextPatientSearchId.IsEnabled = false;
                ComboPatientSearchName.IsEnabled = false;
            }
        }

        private void CheckBoxZone_Check(object sender, RoutedEventArgs e)
        {
            CheckBox chkZone = (CheckBox)sender;
        }

        #endregion

        #region TreeView Events

        private void LoadUserDocument(object sender, MouseButtonEventArgs e)
        {
            try
            {
                TreeViewItem tvi = (TreeViewItem)sender;
                TreeUserDoc tui = (TreeUserDoc)tvi.DataContext;


                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(ApplicationSettings.SERVER_URL + ApplicationSettings.SERVER_REPOSITORY + tui.id);
                webRequest.AllowAutoRedirect = false;
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                String status = response.StatusCode.ToString();
                Debug.WriteLine(" = = = = " + tui.id+" Status:" + status);

                if(status.Equals("OK"))
                {
                    //HttpStatusCode statusCode;                
                    //response = (HttpWebResponse)webRequest.GetResponse();
                    //statusCode = response.StatusCode;

                    BrowserPdfViewer.Navigate(ApplicationSettings.SERVER_URL + ApplicationSettings.SERVER_REPOSITORY + tui.id);
                    //BrowserPdfViewer.Source = new Uri(response.ResponseUri.AbsoluteUri);
                    //BrowserPdfViewer.Source = new Uri(@"C:\Optima Project Proposal.pdf");
                    //BrowserPdfViewer.NavigateToString("<html><head></head><body><iframe src='http://153.121.40.23:8080/plan/PDF_Repository/H22_8/Patient_Docs/2/OTHE-000001/18/2014031916023347.pdf'></iframe></body></html>");

                    //var PdfUC = new PDFViewerUC(response.ResponseUri.AbsoluteUri);
                    //this.AcrobatPdfViewer.Child = PdfUC;
                }

            }
            catch (Exception)
            {
               // var PdfUC = new PDFViewerUC("http://153.121.40.23:8080/plan/PDF_Repository/H22_8/Patient_Docs/2/OTHE-000001/18/2014031916023347.pdf");
                //this.AcrobatPdfViewer.Child = PdfUC;
               
                BrowserPdfViewer.NavigateToString("<html><head><body><p><b style='color:red;'>"+ErrorMessage.DOCUMENT_LOADING_ERROR+"</b></p></body></head></html>");
                //BrowserPdfViewer.NavigateToString("<html><head></head><body style='margin: 0px;'><iframe width='100%' height='100%' style'border-width: 0px;' src='http://153.121.40.23:8080/plan/PDF_Repository/H22_8/Patient_Docs/2/OTHE-000001/18/2014031916023347.pdf' style></iframe></body></html>");
                //BrowserPdfViewer.Navigate("http://153.121.40.23:8080/plan/PDF_Repository/H22_8/Patient_Docs/2/OTHE-000001/18/2014031916023347.pdf");

                //MoonPdfPanel p = new MoonPdfPanel();

                //WebClient wc = new WebClient();

                //byte[] bytes = File.ReadAllBytes("http://153.121.40.23:8080/plan/PDF_Repository/H22_8/Patient_Docs/2/OTHE-000001/18/2014031916023347.pdf");
                //byte[] bytes = wc.DownloadData("http://153.121.40.23:8080/plan/PDF_Repository/H22_8/Patient_Docs/2/OTHE-000001/18/2014031916023347.pdf");
                
                //var source = new MemorySource(bytes);
                //MoonPDFViewer.Open(source);
                }
        }

        private void NodeMouselick(object sender, MouseButtonEventArgs e)
        {
            TreeViewItem tvi = (TreeViewItem)sender;
            if (tvi != null)
                tvi.IsExpanded = !tvi.IsExpanded;
            e.Handled = true;

        }

        private void TreeViewOrgatizationMouseClickUp(object sender, MouseButtonEventArgs e)
        {
            TextBlock documentName = (TextBlock)sender;
            string fullPath = documentName.ToolTip.ToString();

            string pdfPath = ConfigurationManager.AppSettings["organization_documents"];

            //var PdfUC = new PDFViewerUC(new System.IO.FileInfo(fullPath).FullName);
            //this.AcrobatPdfViewer.Child = PdfUC;

            BrowserPdfViewer.Source = new Uri(new System.IO.FileInfo(fullPath).FullName);//new Uri(new System.IO.FileInfo(@pdfPath + "\\" + documentName.Text).FullName);
        }

        private void TreeViewPatientMouseClickUp(object sender, MouseButtonEventArgs e)
        {
            TextBlock documentName = (TextBlock)sender;
            string fullPath = documentName.ToolTip.ToString();
            string pdfPath = ConfigurationManager.AppSettings["patient_documents"];
            //var PdfUC = new PDFViewerUC(new System.IO.FileInfo(fullPath).FullName);
            //this.AcrobatPdfViewer.Child = PdfUC;

            BrowserPdfViewer.Source = new Uri(new System.IO.FileInfo(fullPath).FullName);//new Uri(new System.IO.FileInfo(@pdfPath + "\\" + documentName.Text).FullName);
        }

        #endregion
    }
}
